package net.butfly.bus.config.bean;

import java.util.Map;

import net.butfly.bus.context.Constants;
import net.butfly.bus.exception.BusRuntimeException;
import net.butfly.bus.filter.FilterBase;

public class FilterBean implements Comparable<FilterBean> {
	public enum Signal {
		goon, skipNext, toMain, toEnd, quit
	}

	private String title;
	private int order;
	private Signal exceptionHandler = Signal.quit;
	private Class<? extends FilterBase> clazz;
	private Map<String, String> initParamMap;
	private FilterBase base;

	@SuppressWarnings("unchecked")
	public FilterBean(String title, int order, String exceptionHandler, Map<String, String> initParams, String clazz) {
		this.title = title;
		this.order = order;
		if (exceptionHandler != null) {
			try {
				this.exceptionHandler = Signal.valueOf(exceptionHandler);
			} catch (Exception ex) {
				throw new BusRuntimeException(Constants.UserError.FILTER_INVOKE,
						"Failed in ExceptionHandler initialization for filter " + clazz
								+ ", please check class or filter configuration.");
			}
		}
		initParamMap = initParams;

		if (clazz != null) {
			try {
				this.clazz = (Class<? extends FilterBase>) Class.forName(clazz);
				base = this.clazz.newInstance();
			} catch (Exception ex) {
				throw new BusRuntimeException(Constants.UserError.FILTER_INVOKE, "Failed in instantiation of filter "
						+ clazz + ", please check filter configuration.");
			}
			base.setInitParamMap(initParamMap);
		}
	}

	public String getTitle() {
		return title;
	}

	public int getOrder() {
		return order;
	}

	public Map<String, String> getInitParamMap() {
		return initParamMap;
	}

	public FilterBase getFilter() {
		return base;
	}

	public Signal getExceptionSignal() {
		return exceptionHandler;
	}

	// ------------------------------------------------------------------------
	public int compareTo(FilterBean filter) {
		return filter.getOrder() - order;
	}

	public Class<? extends FilterBase> getFilterClz() {
		return clazz;
	}

}
